//
//  XKMineViewController.m
//  XKJY
//
//  Created by xuyaguang on 2017/1/10.
//  Copyright © 2017年 xiaokang100. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>

#import "XKMineViewController.h"
#import "XKAboutUsController.h"
#import "XKCertificationController.h"
#import "XKUpdateLoginPwdController.h"
#import "XKUpdateTradePwdController.h"
#import "XKBankCardManageController.h"
#import "XKScanQRViewController.h"
#import "XKQRCoderController.h"

#import "XKMineHeaderCell.h"
#import "XKMineAssetsCell.h"
#import "XKMineFunctionCell.h"

#import "XKMineFunctionCellModel.h"

#import "XKMainNavigationController.h"
#import "XKLoginViewController.h"

#import "XKMineLevelUpController.h"

#import "XKMainTabBarController.h"
#import "XKAuthoLoginController.h"
#import "XKAuthoErrorController.h"

#import "XKSupportController.h"

static NSString *XKMineHeaderCellID   = @"XKMineHeaderCellReusableIdentifier";
static NSString *XKMineAssetsCellID   = @"XKMineAssetsCellReusableIdentifier";
static NSString *XKMineFunctionCellID = @"XKMineFunctionrCellReusableIdentifier";

@interface XKMineViewController () <XKScanQRViewControllerDelegate>
@property (nonatomic, strong) NSArray<XKMineFunctionCellModel *> *functionCellDataArray;
@property (nonatomic, strong) UIButton *logoutButton;
@property (nonatomic, strong) UIButton *qrCodeButton;
@property (nonatomic, copy) NSString *qr_url;
@end

@implementation XKMineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTableView];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadUserCertificationState];
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotoTradeView) name:@"levelupgotobuywos" object:nil];
}

#pragma mark - gotoTradeView
- (void)gotoTradeView {
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    XKMainTabBarController *tarBarVC = (XKMainTabBarController *)keyWindow.rootViewController;
    tarBarVC.selectedIndex = 1;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    [self loadUserCertificationState];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self addNavigationButton];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self removeNavigationButton];
}

#pragma mark - 注销和分享
- (void)addNavigationButton {
    
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    
    UIButton *logoutButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [logoutButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [logoutButton setImage:[UIImage imageNamed:@"account_logout"] forState:UIControlStateNormal];
    [logoutButton addTarget:self action:@selector(logoutButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [keyWindow addSubview:logoutButton];
    [logoutButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10*Scale_W);
        make.top.mas_equalTo(24*Scale_W);
        make.size.mas_equalTo(CGSizeMake(40*Scale_W, 40*Scale_W));
    }];
    
    
    UIButton *qrCodeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [qrCodeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [qrCodeButton setImage:[UIImage imageNamed:@"qr_scan"] forState:UIControlStateNormal];
    [qrCodeButton addTarget:self action:@selector(qr_code:) forControlEvents:UIControlEventTouchUpInside];
    [keyWindow addSubview:qrCodeButton];
    [qrCodeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-10*Scale_W);
        make.centerY.mas_equalTo(logoutButton);
        make.size.mas_equalTo(CGSizeMake(40*Scale_W, 40*Scale_W));
    }];
    
    
    _logoutButton = logoutButton;
    _qrCodeButton = qrCodeButton;
}

#pragma mark - 我的二维码
- (void)qr_code:(UIButton *)sender {
    if ([self isVerify]) {
        
        if (![_qr_url isValidUrl]) {
            [SVProgressHUD showInfoWithStatus:@"信息获取失败"];
            return;
        }
        
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) {
            [UIAlertController showAlertView:self title:@"未获得相机访问权限!" message:@"" cancelButtonTitle:@"取消" confirmBtnTitle:@"去授权" cancleBlock:^{
                
            } confirmBlock:^{
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if (SYSTEM_VERSION_LESS_THAN(@"10")) {
                    [[UIApplication sharedApplication] openURL:url];
                } else {
                    [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
                }
            }];
            return;
        }
        
        XKScanQRViewController *vc = [XKScanQRViewController new];
        vc.delegate = self;
        vc.qr_url = _qr_url;
        [self pushViewController:vc];
        
//        XKQRCoderController *myQRCodeVC = [[XKQRCoderController alloc] init];
//        myQRCodeVC.qr_base_url = _qr_url;
//        [self pushViewController:myQRCodeVC];
        
    }
}


#pragma mark - 扫码结果
- (void)qrCodeScanSuccessWithResult:(NSString *)qrCodeContent {
    
    if ([qrCodeContent hasPrefix:@"https://xiaokang100.com/qrcode_login"]) {
        XKAuthoLoginController *authoLoginVC = [[XKAuthoLoginController alloc] init];
        [self presentViewController:authoLoginVC animated:YES completion:nil];
    } else if ([qrCodeContent isValidUrl]){
        if (SYSTEM_VERSION_LESS_THAN(@"10")) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:qrCodeContent]];
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:qrCodeContent] options:@{} completionHandler:nil];
        }
    } else {
        XKAuthoErrorController *errorVC = [[XKAuthoErrorController alloc] init];
        errorVC.errorString = qrCodeContent;
        [self presentViewController:errorVC animated:YES completion:nil];
    }
    
}

#pragma mark - 移除注销和分享按钮
- (void)removeNavigationButton {
    [_logoutButton removeFromSuperview];
    [_qrCodeButton removeFromSuperview];
}



#pragma mark - 注销账号
- (void)logoutButtonClick:(UIBarButtonItem *)sender {
    [UIAlertController showAlertView:self title:@"您确定要注销吗?" message:@"" cancelButtonTitle:@"取消" confirmBtnTitle:@"注销" cancleBlock:^{
        
    } confirmBlock:^{
        [UserDefaults logoutAndRemoveUserDefaults];
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isLoginSuccess"];
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        XKMainNavigationController *nav = [[XKMainNavigationController alloc] initWithRootViewController:[XKLoginViewController new]];
        window.rootViewController = nav;
    }];
}


#pragma mark - 获取用户信息
- (void)loadUserCertificationState {
    @weakify(self);
    [APIManager POSTRequestWith:APIPOSTRequestState_UserInformation parameters:@{} successBlock:^(NSDictionary *successDict) {
        @strongify(self);
        NSLog(@"%@",[NSString jsonToString:successDict]);
        
        NSString *url = successDict[@"data"][@"share_url"];
        self.qr_url = [url isValidUrl] ? url : @"";
        
        [self.tableView.mj_header endRefreshing];
        if ([UserDefaults setObjectWithData:successDict[@"data"]]) {
            [self.tableView reloadData];
        } else {
            [SVProgressHUD showErrorWithStatus:@"信息获取失败!"];
        }
    } failureBlock:^(NSDictionary *failureDict) {
        [self.tableView.mj_header endRefreshing];
    } errorBlock:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
    }];
}


#pragma mark - 会员升级
- (void)levelUPWithType:(NSInteger)levelUPType {  //levelUPType 升级方式(2种子/1人民币)

    // 断实名认证情况
    if ([self isVerify]) {
        [self pushToLevelUpVCWithLevelUPType:levelUPType];
    }

}

- (void)pushToLevelUpVCWithLevelUPType:(NSInteger)levelUPType {
    XKMineLevelUpController *levelUpVC = [XKMineLevelUpController new];
    levelUpVC.currentLevel = [UserDefaults objectWithKey:@"level"];
    levelUpVC.levelUPType = [NSString stringWithFormat:@"%zd",levelUPType];
    levelUpVC.title = @"会员升级";
    levelUpVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:levelUpVC animated:YES];
}


#pragma mark - 配置tableView
- (void)setTableView {
    self.tableView.scrollEnabled = YES;
    self.tableView.bounces = YES;
    self.tableView.contentInset = UIEdgeInsetsMake(-20, 0, 0, 0);
}

- (NSArray *)functionCellDataArray {
    NSMutableArray *mutableArray = [NSMutableArray array];
    if (!_functionCellDataArray) {
        //路径
        NSString *path = [[NSBundle mainBundle] pathForResource:@"MineFunctions"ofType:@"plist"];
        
        //读取
        NSArray *tempArray = [NSArray arrayWithContentsOfFile:path];
        [tempArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            XKMineFunctionCellModel *model = [XKMineFunctionCellModel mj_objectWithKeyValues:tempArray[idx]];
            [mutableArray addObject:model];
        }];
    }
    return mutableArray.copy;
}

#pragma mark - 数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 3) {
        return 3;
    } else {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    switch (section) {
        case 0:
        case 1:
        case 2:return 0.01;
        case 3:
        case 4:return 5;
        default:return 0.01;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [UIView new];
    v.backgroundColor = kBaseGrayColor;
    return v;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        XKMineHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:XKMineHeaderCellID];
        if (cell == nil) {
            cell = [[XKMineHeaderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:XKMineHeaderCellID];
        }
        
        cell.nickString = [UserDefaults objectWithKey:@"nick"];
        cell.userLevelString = [UserDefaults objectWithKey:@"level"];
        cell.iconString = @"";
        @weakify(self);
        
        cell.levelNameLabelBlock = ^{
            @strongify(self);
            [self levelUPWithType:1];
        };
        cell.levelUpBlock = ^() {
            @strongify(self);
            [self levelUPWithType:2];
        };
        cell.fastLevelUpBlock = ^() {
            @strongify(self);
            [self levelUPWithType:1];
        };
        return cell;
        
        
    } else if (indexPath.section == 1) {
        XKMineAssetsCell *cell = [tableView dequeueReusableCellWithIdentifier:XKMineAssetsCellID];
        if (cell == nil) {
            cell = [[XKMineAssetsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:XKMineAssetsCellID];
        }
        
        cell.dataArray = @[[UserDefaults objectWithKey:@"wopnum"], [UserDefaults objectWithKey:@"rmb"], [UserDefaults objectWithKey:@"wopincome"], [UserDefaults objectWithKey:@"member_points"]];
        return cell;
        
        
    } else if (indexPath.section == 2) {
        XKMineFunctionCell *cell = [tableView dequeueReusableCellWithIdentifier:XKMineFunctionCellID];
        if (cell == nil) {
            cell = [[XKMineFunctionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:XKMineFunctionCellID];
        }
        XKMineFunctionCellModel *model = self.functionCellDataArray[indexPath.row];
        cell.titleString = model.title;
        cell.iconImgName = model.icon;
        if ([model.type isEqualToString:@"1"]) {
            cell.certifiedState = [[UserDefaults objectWithKey:@"status"] integerValue];
        } else {
            cell.certifiedState = CertifiedState_HIDE;
        }
        return cell;
        
        
    } else if (indexPath.section == 3) {
        XKMineFunctionCell *cell = [tableView dequeueReusableCellWithIdentifier:XKMineFunctionCellID];
        if (cell == nil) {
            cell = [[XKMineFunctionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:XKMineFunctionCellID];
        }
        XKMineFunctionCellModel *model = self.functionCellDataArray[indexPath.row + 1];
        cell.titleString = model.title;
        cell.iconImgName = model.icon;
        if ([model.type isEqualToString:@"1"]) {
            cell.certifiedState = [[UserDefaults objectWithKey:@"status"] integerValue];
        } else {
            cell.certifiedState = CertifiedState_HIDE;
        }
        return cell;
        
        
    } else {
        XKMineFunctionCell *cell = [tableView dequeueReusableCellWithIdentifier:XKMineFunctionCellID];
        if (cell == nil) {
            cell = [[XKMineFunctionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:XKMineFunctionCellID];
        }
        XKMineFunctionCellModel *model = self.functionCellDataArray.lastObject;
        cell.titleString = model.title;
        cell.iconImgName = model.icon;
        if ([model.type isEqualToString:@"1"]) {
            cell.certifiedState = [[UserDefaults objectWithKey:@"status"] integerValue];
        } else {
            cell.certifiedState = CertifiedState_HIDE;
        }
        return cell;
    }
}


#pragma mark - cell点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (indexPath.section == 2) {
        [self isVerify] ? [SVProgressHUD showInfoWithStatus:@"您已通过认证!"]:@"";
    } else if (indexPath.section == 3) {
        switch (indexPath.row) {
            case 0: { [self isVerify] ? [self pushViewController:[XKUpdateTradePwdController new]] : @""; } break;
            case 1: { [self pushViewController:[XKUpdateLoginPwdController new]]; } break;
            case 2: { [self isVerify] ? [self pushViewController:[XKBankCardManageController new]] : @""; } break;
            default: break;
        }
    } else if (indexPath.section == 4) {
        [self pushViewController:[XKAboutUsController new]];
    }
}

#pragma mark - 验证用户实名状态
- (BOOL)isVerify {
    NSString *state = [UserDefaults objectWithKey:@"status"];
    if ([state isEqualToString:@"0"]) {
        [self pushViewController:[XKCertificationController new]];
        return NO;
    } else if ([state isEqualToString:@"2"]) {
        [SVProgressHUD showInfoWithStatus:@"实名认证中..."];
        return NO;
    } else if ([state isEqualToString:@"1"]) {
        return YES;
    } else {
        return NO;
    }
}

#pragma mark - 控制器跳转
- (void)pushViewController:(UIViewController *)viewController {
    viewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
